<?php

/**
 * @author luhua
 */
class EmailTaskListModel extends Model
{

    /**
     * 插入任务列表
     * @param array $task 所属任务标识
     * return boolen 
     */
    public function insertTaskList($task,$delete = false) {
        $emailModel = M('Email');
        $emails = $emailModel->order('email_id desc')->select();
        $beginAtDate = date('Y-m-d', strtotime($task['begin_at']));
        $nextSendAtDate = $beginAtDate . ' ' . $task['begin_time'];
        if(strtotime($nextSendAtDate) <= strtotime($task['begin_at'])) {
            $nextSendAt = strtotime($nextSendAtDate) + 3600*24;
        } else {
            $nextSendAt = strtotime($nextSendAtDate);
        }
        $this->startTrans();
        if($delete) {
            $this->where("task_id = " . $task['task_id'])->delete();
        }
        foreach ($emails as $email) {
            $data['task_id'] = $task['task_id'];
            $data['template_id'] = $task['template_id'];
            $data['begin_at'] = $task['begin_at'];
            $data['begin_time'] = $task['begin_time'];
            $data['interval'] = $task['interval'];
            $data['last_send_status'] = '0';
            $data['last_send_at'] = 0;
            $data['send_count'] = 0;
            $data['next_send_at'] = $nextSendAt;
            $data['email'] = $email['email'];
            $result = $this->data($data)->add();
            if (!$result) {
                break;
            }
        }
        if (false !== $result) {
            $this->commit();
            return true;
        } else {
            $this->rollback();
            return false;
        }
    }

}

?>
